/*
 * Created on 29/04/2008
 */
package com.apbetioli.mapr.map;

import com.apbetioli.mapr.place.dao.PlacesDaoFactory;
import com.apbetioli.mapr.place.entity.GeoPoint;
import com.apbetioli.mapr.place.entity.Place;
import com.apbetioli.mapr.util.properties.PropertiesLoaderImpl;
import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author Alexandre Parra Betioli
 */
public class MapServlet extends HttpServlet {

    //Initial values
    double latitude  = Double.parseDouble(PropertiesLoaderImpl.getValue("config.properties", "gmaps.latitude"));
    double longitude = Double.parseDouble(PropertiesLoaderImpl.getValue("config.properties", "gmaps.longitude"));
    double altitude  = Double.parseDouble(PropertiesLoaderImpl.getValue("config.properties", "gmaps.altitude"));
    
    String gmapsKey = PropertiesLoaderImpl.getValue("config.properties", "gmaps.api.key");
    String title    = PropertiesLoaderImpl.getValue("messages.properties", "page.title");
    
    //String kmlDir = PropertiesLoaderImpl.getValue("config.properties", "kml.url");
    //String kmlDir = System.getProperty("user.home") + File.separator + PropertiesLoaderImpl.getValue("config.properties", "kml.generator.folder");
    
    int width  = Integer.parseInt(PropertiesLoaderImpl.getValue("config.properties", "gmaps.width"));
    int height = Integer.parseInt(PropertiesLoaderImpl.getValue("config.properties", "gmaps.height"));

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            //Validation

            String projectKeyParam = request.getParameter("key");
            String latitudeParam   = request.getParameter("latitude");
            String longitudeParam  = request.getParameter("longitude");
            String placeNameParam  = request.getParameter("name");

            String res = validate(projectKeyParam, latitudeParam, longitudeParam, placeNameParam);
            if (res != null) {
                out.println(res);
                return;
            }

            // Building the page

            out.println("<html>");
            out.println("<head>");
            out.println("<meta http-equiv='content-type' content='text/html; charset=utf-8'/>");
            out.println("<title>" + title + "</title>");

            // Load Google's script


            out.println("<script src='http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=" + gmapsKey + "' type='text/javascript'/>");

            // Load own script 

            out.println("<script src='./javascript/mapScript.js' type='text/javascript'/>");
            out.println("</head>");

            // Load map in a given position

            String kmlUrl = "KmlLoader?key=" + projectKeyParam;

            out.println("<body onload=\"initialize('" + kmlUrl + "', " + latitude + ", " + longitude + ", " + altitude + " )\"  onunload=\"GUnload()\" >");
            out.println("<div id='map_canvas' style='width: " + width + "px; height: " + height + "px; float:left; border: 1px solid black;'></div>");
            
            out.println("<a href=\"" + kmlUrl + "\">KML</a>");
            
            out.println("</body>");
            out.println("</html>");

        } finally {
            out.close();
        }
    }

    private String validate(String projectKey, String slatitude, String slongitude, String placeName) {

        String example = "<br><br>Example: ...Map?key=123456789&name=Serra+da+Lagoa<br><br>OR<br><br>" +
                "...Map?key=12345679&latitude=12.3456&longitude=98.7654321";
        
        
        if (projectKey == null) {
            return "Please inform the key" + example;
        }

        if (placeName == null) {

            if (slatitude == null || slongitude == null) {
                return "Please inform the place's name or latitude and longitude"+ example;
            }

        }
        else {
            
            placeName = placeName.replaceAll("+", " ");
            Place place = PlacesDaoFactory.getInstance(true).findByName(placeName);
            if( place != null ) {
                System.out.println( place );
                
                GeoPoint gp = place.getGeoPoint();
                if( gp != null ) {
                    latitude  = gp.getLatitude();
                    longitude = gp.getLongitude();
                }
            }
            
            return null;
        }

        try {
            latitude = Double.parseDouble(slatitude);

            if ((latitude < -90) || (latitude > 90)) {
                throw new Exception();
            }

        } catch (Exception e) {
            return "Latitude should be a real number between -90 and 90";
        }

        try {
            longitude = Double.parseDouble(slongitude);

            if ((longitude < -180) || (longitude > 180)) {
                throw new Exception();
            }

        } catch (Exception e) {
            return "Longitude should be a real number between -180 and 180";
        }

        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "The map";
    }

    // </editor-fold>
}
